<template>
  <div class="app-container">
    <div>
      <div class="in-common" @click="viewInfoClinic">{{viewInfoTitle}}</div>
    </div>
    <el-row :gutter="0" style="height: calc(100% - 10px);">
      <el-col :span="isPatientClickType ? 24 : 19" class="height-auto"
              style="border:1px solid #7a7a7a;border-radius:5px;">
        <clinic-doctor-index ref="clinicDoctorIndexRef" :is-otc-outpatient="true"
                             :is-to-convenient-outpatient="true" style="height: calc(100% - 18px)"
                             @other-click="patientClick"/>
        <div style="float: right;margin-right: 10px;margin-top: -8px;">
          发药药房:
          <el-select v-model="queryParams.implementDept" class="ml5 mr20"
                     placeholder="请输入发药药房" style="width: 100px" @change="drugVsDeptChange">
            <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"
                       :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>
          </el-select>
          <el-button type="success"
                     @click="chargeOk">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            收费
          </el-button>
          <el-button type="danger"
                     @click="refundApplication">
            <svg-icon class="mr5" icon-class="refundApplication"/>
            确认退费
          </el-button>
          <el-button plain type="primary"
                     @click="grantInfoOkFun(5,null)">
            <svg-icon class="mr5" icon-class="grant-info"/>
            药品发放
          </el-button>
        </div>
      </el-col>
      <el-col :span="isPatientClickType ? 0 : 5" class="height-auto">
        <div class="mb10" style="height: 50%;">
          <div class="div-background-color" style="padding-bottom: 5px;padding-top: 5px;">
            <span class="ml10">今日收费</span>
            <el-tooltip class="item" content="刷新" effect="dark" placement="top">
              <el-button class="mr10" style="float: right;" type="primary"
                         @click="getList()">
                <template #icon>
                  <i-ep-search/>
                </template>
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" content="历史收费记录" effect="dark" placement="top">
              <el-button class="mr10" style="float: right;" type="warning"
                         @click="historyClick(1,'')">
                <template #icon>
                  <svg-icon icon-class="history"/>
                </template>
              </el-button>
            </el-tooltip>
          </div>
          <el-table :border="true" :data="outpFeesMasterList" :header-cell-style="$headerCellStyle"
                    :stripe="true"
                    height="calc(100% - 75px)" highlight-current-row @row-click="rowFeesClick">
            <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="left" label="缴费标志"
                             prop="chargeFlag" width="90">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                               :value="scope.row.chargeFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" fixed="left" label="患者姓名" prop="name" width="80"/>
            <el-table-column :align="'center'" label="收费时间" prop="createTime" width="130">
              <template #default="scope">
                                                    <span>{{
                                                        $parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
                                                      }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="总费用" prop="costs" width="110">
              <template #default="scope">
                                                <span class="ys-css">{{
                                                    // parseFloat(scope.row.costs - scope.row.refundCharges + "").toFixed(2)
                                                    parseFloat(scope.row.costs).toFixed(2)
                                                  }}</span>元
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="收据号" prop="feesNo" width="130">
              <template #default="scope">
                <span style="color: rgb(51, 91, 249)">{{ scope.row.feesNo }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="应收费用" prop="charges" width="110">
              <template #default="scope">
                                                    <span class="ys-css">{{
                                                        parseFloat(scope.row.charges).toFixed(2)
                                                      }}</span>元
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="支付方式" prop="moneyType" width="65">
              <template #default="scope">
                <el-popover :title="scope.row.name + ' | 收据号' + scope.row.feesNo" :width="270"
                            placement="right"
                            trigger="hover">
                  <template #reference>
                    <el-button type="primary">详情</el-button>
                  </template>
                  <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
                    <el-descriptions-item v-for="(item, index) in scope.row.paymentsMoneyVoList"
                                          :key="index"
                                          min-width="80px">
                      <template #label>
                        <div style="display: flex">
                          <div style="flex: 1">
                                                                            <span style="font-weight: bold">{{
                                                                                item.moneyTypeName
                                                                              }}
                                                                            </span>
                          </div>
                        </div>
                      </template>
                      <span class="ys-css">{{ parseFloat(item.charges).toFixed(2) }}</span>元
                    </el-descriptions-item>
                  </el-descriptions>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="收款人"
                             prop="operationUserName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="退费号"
                             prop="refundedFeesNo"
                             width="110"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="退费人"
                             prop="refundedPersonName" width="80"/>
            <el-table-column :align="'left'" label="退费金额" prop="refundCharges" width="110">
              <template #default="scope">
                                                    <span class="ret-ys-css">{{
                                                        parseFloat(scope.row.refundCharges + "").toFixed(2)
                                                      }}</span>元
              </template>
            </el-table-column>
            <!--                        <el-table-column :align="'center'" label="结账号" prop="acctNo" width="65"/>-->
            <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作"
                             width="80">
              <template #default="scope">
                <template v-if="scope.row.chargeFlag === '2'">
                  <el-tooltip class="item" content="打印" effect="dark" placement="top">
                    <el-button circle type="primary">
                      <template #icon>
                        <i-ep-printer/>
                      </template>
                    </el-button>
                  </el-tooltip>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <div class="div-background-color">
            <div class="ml10 mr10">
              <div style="border-bottom: 1px dotted #1a1a1a;">
                <div style="display: flex">
                  <div style="flex: 0.5;font-size: 12px;margin-top: 2px;">收(元)</div>
                  <div style="flex: 1;font-size: 12px">总计:<span class="ys-css">{{ total }}</span>
                  </div>
                  <div style="flex: 1;font-size: 12px">自费:<span class="ys-css">{{
                      selfFinancing
                    }}</span>
                  </div>
                  <div style="flex: 1;font-size: 12px">医保:<span
                    class="ys-css">{{ medicalCharge }}</span>
                  </div>
                </div>
              </div>
              <div style="border-bottom: 1px dotted #1a1a1a">
                <div style="display: flex;color: #fd0101">
                  <div style="flex: 0.5;font-size: 12px">退(元)</div>
                  <div style="flex: 1;font-size: 12px">总计:<span
                    class="ret-ys-css">{{ returnTotal }}</span>
                  </div>
                  <div style="flex: 1;font-size: 12px">自费:<span
                    class="ret-ys-css">{{ returnSelfFinancing }}</span>
                  </div>
                  <div style="flex: 1;font-size: 12px">医保:<span
                    class="ret-ys-css">{{ returnMedicalCharge }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="height: 50%;">
          <div class="div-background-color" style="padding-bottom: 5px; ">
            <span class="ml5" style="font-size: 13px;padding-top: 5px">今日发药</span>
            <el-tooltip class="item" content="刷新" effect="dark" placement="top">
              <el-button class="mr10" style="float: right;" type="primary"
                         @click="getPrescriptionList()">
                <template #icon>
                  <i-ep-search/>
                </template>
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" content="历史发药记录" effect="dark" placement="top">
              <el-button class="mr10" style="float: right;" type="warning"
                         @click="historyClick(6,'')">
                <template #icon>
                  <svg-icon icon-class="history"/>
                </template>
              </el-button>
            </el-tooltip>
          </div>
          <el-table ref="applyTableRef" :border="true" :data="prescriptionApplyList" :header-cell-style="$headerCellStyle"
                    :stripe="true"
                    height="calc(100% - 65px)" highlight-current-row @row-click="grantInfoOkFun(5,$event)">
            <el-table-column :align="'left'" label="领药人信息" prop="name" width="130">
              <template #default="scope">
                {{ scope.row.name }}
                <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
                {{ scope.row.age }} 岁{{ scope.row.ageMonth }} 月
                <!-- {{ scope.row.ageDay }}天 -->
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="发药标志"
                             prop="confirmFlag"
                             width="90">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['grant_flag']" :value="scope.row.confirmFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方号" prop="applyNo"
                             width="100"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方属性"
                             prop="prescAttr"
                             width="80">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['prescription_type']"
                               :value="scope.row.prescAttr"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="80"/>
            <el-table-column :align="'center'" label="开单科室" prop="applyDeptName"/>
            <el-table-column :align="'center'" label="开单时间" prop="createTime" width="130"/>
            <!-- <el-table-column :align="'center'" label="发药药房" prop="implementDepName" /> -->
          </el-table>
          <div class="div-background-color">
            <div class="ml10 mr10">
              <div style="border-bottom: 1px dotted #1a1a1a">
                <div style="display: flex">
                  <div style="flex: 0.5;font-size: 11px">处方数</div>
                  <div style="flex: 1;font-size: 11px">总计:<span class="ys-css">{{
                      drugTotal
                    }}</span>
                  </div>
                  <div style="flex: 1;font-size: 11px">未发方数:<span class="ys-css">{{
                      noIssueDrugTotal
                    }}</span>
                  </div>
                  <div style="flex: 1;font-size: 11px">发方数:<span class="ys-css">{{
                      issueDrugTotal
                    }}</span>
                  </div>
                  <div class="ret-ys-css" style="flex: 1;font-size: 11px">退方数:<span>{{
                      returnDrugTotal
                    }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog v-model="historyOpen" :close-on-click-modal="false" :title="historyTitle" append-to-body width="90%"
               @close="historyCancel">
      <outpatient-fee-records v-if="historyType === 1" ref="outpatientFeeRecordsRef"/>
      <outpatient-fee-index v-else-if="historyType === 3" ref="outpatientFeeIndexRef"
                            @convenient-charge-ok="convenientChargeOk"/>
      <outpatient-refund v-else-if="historyType === 4" ref="outpatientRefundRef"
                         @convenient-refund-charge-ok="convenientRefundChargeOk"/>
      <grant v-else-if="historyType === 5" ref="grantRef" :adaptive-height="500"
             @convenient-grant-ok="convenientGrantOk"/>
      <issued-grant v-else-if="historyType === 6" ref="issuedGrantRef" :adaptive-height="500"
                    @convenient-issued-grant-ok="convenientGrantOk"/>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import ClinicDoctorIndex from "@/views/doctor/clinicDoctor/index.vue"
import {useUserStoreHook} from "@/store/modules/user";
import {listOutpFeesMaster} from "@/api/finance/outpFeesMaster.ts";
import {listPrescriptionApply} from "@/api/patient/prescriptionApply.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {listClinicOrdersTotality} from "@/api/clinicOrder/clinicOrders";
import outpatientFeeRecords from "@/views/finance/outpFees/query/outpatientFeeRecords.vue";
import outpatientFeeIndex from "@/views/finance/outpFees/index.vue";
import outpatientRefund from "@/views/finance/outpFees/query/outpatientRefund.vue"
import grant from '@/views/drug/distributeMedication/grant.vue';
import issuedGrant from '@/views/drug/distributeMedication/issuedGrant.vue';
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
const {proxy} = getCurrentInstance() as any;
const historyOpen = ref(false)
const historyTitle = ref("")
const historyType = ref<number>(1)
const clinicDoctorIndexRef = ref()
const outpatientFeeRecordsRef = ref()
const outpatientFeeIndexRef = ref()
const outpatientRefundRef = ref()
const grantRef = ref()
const issuedGrantRef = ref()
const outpFeesMasterList = ref<any>([]);
// 左侧患者列表点击事件状态
const isPatientClickType = ref<any>(false)
// 左侧患者列表点击事件按钮label
const viewInfoTitle = ref<any>("查看收费-发药信息")
// 药房list
const drugVsDeptList = ref<any>([])
// 主记录列表
const prescriptionApplyList = ref<any>([])
const dictDataMap = ref(
  dictStore.isTypeGetData("charge_flag_dict", "sys_yes_no", "bill_item_class_dict",
    "sys_user_sex", "prescription_type", "grant_flag")
);
const queryParams = ref<any>({
  // pageNum: 1,
  // pageSize: 10,
  orgId: userInfo.orgId,
  implementDept: '',
  inoroutFlag: '4'
});
// 收费  总计
const total = ref<number>(0.00)
// 收费  自费
const selfFinancing = ref<number>(0.00)
// 收费  医保
const medicalCharge = ref<number>(0.00)
// 退费  总计
const returnTotal = ref<number>(0.00)
// 退费  自费
const returnSelfFinancing = ref<number>(0.00)
// 退费  医保
const returnMedicalCharge = ref<number>(0.00)
// 总方数
const drugTotal = ref<number>(0)
// 发方数
const issueDrugTotal = ref<number>(0)
// 未方数
const noIssueDrugTotal = ref<number>(0)
// 退方数
const returnDrugTotal = ref<number>(0)

const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);

/** 查询表集合 */
function getList() {
  queryParams.value.operationUserName = userInfo.nickName
  queryParams.value.isOtc = '1'
  listOutpFeesMaster(proxy.$addDateRange(queryParams.value, dateRange.value)).then(
    (response: any) => {
      const data = response.data;
      outpFeesMasterList.value = data;
      let thisTotal = 0 as number
      let thisSelfFinancing = 0 as number
      let thisMedicalCharge = 0 as number
      let thisReturnTotal = 0 as number
      let thisReturnSelfFinancing = 0 as number
      let thisReturnMedicalCharge = 0 as number
      data.forEach((item) => {
        if (item.chargeFlag != '4') {
          // 获取支付方式
          const paymentsMoneyVoList = item.paymentsMoneyVoList
          thisTotal = thisTotal += Number(item.charges)
          let payWayDictGroup1 = payWayDictGroup(paymentsMoneyVoList);
          thisSelfFinancing = thisSelfFinancing += Number(payWayDictGroup1.selfFinancing)
          thisMedicalCharge = thisMedicalCharge += Number(payWayDictGroup1.medicalCharge)
        } else if (item.chargeFlag === '4') {
          // 获取支付方式
          const paymentsMoneyVoList = item.paymentsMoneyVoList
          thisReturnTotal = thisReturnTotal += Number(item.charges)
          let payWayDictGroup2 = payWayDictGroup(paymentsMoneyVoList);
          thisReturnSelfFinancing = thisReturnSelfFinancing += Number(payWayDictGroup2.selfFinancing)
          thisReturnMedicalCharge = thisReturnMedicalCharge += Number(payWayDictGroup2.medicalCharge)
        }
      })
      total.value = Number(thisTotal.toFixed(2))
      selfFinancing.value = Number(thisSelfFinancing.toFixed(2))
      medicalCharge.value = Number(thisMedicalCharge.toFixed(2))
      returnTotal.value = Number(thisReturnTotal.toFixed(2))
      returnSelfFinancing.value = Number(thisReturnSelfFinancing.toFixed(2))
      returnMedicalCharge.value = Number(thisReturnMedicalCharge.toFixed(2))
    }
  );
}

/**
 * 计算收费支付方式分组
 * @param paymentsMoneyVoList
 */
function payWayDictGroup(paymentsMoneyVoList: any) {
  // 自费
  let payWaySelfFinancing: number = 0
  // 医保
  let payWayMedicalCharge: number = 0
  paymentsMoneyVoList.forEach((item: any) => {
    if (item.moneyType === '1' || item.moneyType === '2' || item.moneyType === '3'
      || item.moneyType === '4' || item.moneyType === '5') {
      payWaySelfFinancing = payWaySelfFinancing += Number(item.charges)
    } else {
      payWayMedicalCharge = payWayMedicalCharge += Number(item.charges)
    }
  })
  return {
    "selfFinancing": payWaySelfFinancing.toFixed(2),
    "medicalCharge": payWayMedicalCharge.toFixed(2)
  }
}

/** 查询处方主记录 */
function getPrescriptionList() {
  if (!queryParams.value.implementDept) {
    return ElMessage.error("请先选择发药药房，再进行发药查询操作。");
  }
  queryParams.value.implementUserName = userInfo.nickName
  queryParams.value.isOtc = '1'
  listPrescriptionApply(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    const data = response.data;
    if (data) {
      prescriptionApplyList.value = data.prescriptionApplyVos;
      drugTotal.value = data.drugTotal
      noIssueDrugTotal.value = data.noIssueDrugTotal
      returnDrugTotal.value = data.returnDrugTotal
      issueDrugTotal.value = data.issueDrugTotal
    }
  });
}

/**
 * 弹出框关闭事件
 */
function historyCancel() {
  historyOpen.value = false;
  if (historyType.value === 1) {
    nextTick(() => {
      outpatientFeeRecordsRef.value.convenientToResetQuery()
    })
  } else {

  }
}

/**
 * 历史弹出框打开
 */
function historyClick(type: number, outpFeesMasterId) {
  historyOpen.value = true;
  historyType.value = type
  if (type === 1) {
    historyTitle.value = "历史收费记录";
    nextTick(() => {
      outpatientFeeRecordsRef.value.initQuery(outpFeesMasterId)
    })
  } else if (type === 6) {
    historyTitle.value = "历史发药记录";
    nextTick(() => {
      issuedGrantRef.value.initQuery("", queryParams.value.implementDept)
    })
  } else if (type === 3) {
    historyTitle.value = "收费";
    nextTick(() => {
      outpatientFeeIndexRef.value.convenientClinicNoBlur(proxy.$clinicId)
    })
  }
}

/**
 * 今日收费列表行点击事件
 */
function rowFeesClick(row: any) {
  historyClick(1, row.outpFeesMasterId)
}

/**
 * 今日发药列表行点击事件
 */
function rowDrugClick(row: any) {

}

/**
 * 药品发放/已发放查看记录
 * @param type 5 发药 ；6退药
 * @param row 发药列表行点击 row数据
 */
function grantInfoOkFun(type: number, row: any) {
  if (!row && !proxy.$clinicId) {
    return ElMessage.error("请先选择患者后，再进行发药操作。");
  }
  historyOpen.value = true;
  historyType.value = type
  type = row && row.confirmFlag != '1' ? 6 : 5
  if (type === 5) {
    historyTitle.value = "发药";
    nextTick(() => {
      grantRef.value.initQuery(row.clinicId || proxy.$clinicId, queryParams.value.implementDept)
    })
  } else if (type === 6) {
    historyTitle.value = "已发药";
    historyType.value = type
    nextTick(() => {
      issuedGrantRef.value.initQuery(row.clinicId || proxy.$clinicId, queryParams.value.implementDept)
    })
  }
}

/**
 * 收费
 */
function chargeOk() {
  if (proxy.$clinicId) {
    listClinicOrdersTotality(proxy.$clinicId).then((res: resType) => {
      if (res.data === 0) {
        return ElMessage.error("患者没有需要收费的项目，请开单后再收费")
      } else {
        historyClick(3, "")
      }
    })
  } else {
    return ElMessage.error("请先选择患者")
  }
}

/**
 * 收费完成事件
 */
function convenientChargeOk() {
  historyOpen.value = false
  nextTick(() => {
    clinicDoctorIndexRef.value.convenientRefresh()
  })
  getList()
  getPrescriptionList()
}

/**
 * 确认退费
 */
function refundApplication() {
  if (proxy.$clinicId) {
    listClinicOrdersTotality(proxy.$clinicId).then((res: resType) => {
      historyClick(4, "")
    })
  } else {
    return ElMessage.error("请先选择患者")
  }
}

/**
 * 确认退费完成事件
 */
function convenientRefundChargeOk() {
  historyOpen.value = false
  nextTick(() => {
    clinicDoctorIndexRef.value.convenientRefresh()
  })
  getList()
  getPrescriptionList()
}

/**
 * 发药完成事件
 */
function convenientGrantOk() {
  historyOpen.value = false
  getList()
  getPrescriptionList()
}

/**
 * 药房select 选择事件
 * @param value
 */
function drugVsDeptChange(value) {
  queryParams.value.implementDept = value
  getPrescriptionList()
}

/**
 * 组件卸载事件，清空clinicId和patientId
 */
onUnmounted(() => {
  proxy.$setClinicId("");
  // 设置全局patientId
  proxy.$setPatientId("");
})

// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: userInfo.loginDeptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
    prescriptionTypeChange()
    getPrescriptionList()
  })
}

function prescriptionTypeChange() {
  const index = drugVsDeptList.value.findIndex((item: any) => {
    return "西药房" === item.storageName
  })
  if (index > -1) {
    queryParams.value.implementDept = drugVsDeptList.value[index].storageCode
  }
}
// 左侧患者信息卡，点击事件
function patientClick() {
  isPatientClickType.value = true
  viewInfoTitle.value = "查看收费-发药信息"
}

function viewInfoClinic () {
  isPatientClickType.value = !isPatientClickType.value;
  viewInfoTitle.value = isPatientClickType.value ? '查看收费-发药信息' :'隐藏'
}
getList()
onMounted(() => {
  getDrugVsDeptListFun()
})
</script>

<script lang="ts">
export default {
  name: "OtcSaleOutpatient"
}
</script>

<style scoped>
:deep(.right-card .el-card__body) {
  height: 50%;
  padding-right: 10px;
  padding-left: 10px;

}

.div-background-color {
  background-color: #d6e7f1;
}

:deep(.el-tabs__content) {
  padding: 2px !important;
}

:deep(.el-drawer.rtl) {
  bottom: 0;
  height: 93%;
  top: 50px;
}

.in-common {
  top: 80px;
  width: 22px;
  background-color: #1ba811;
}


</style>
